package org.ttitfly.ttcore.dao.account;
import java.util.List;



import org.hibernate.Query;
import org.hibernate.QueryException;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.hibernate.HibernateDao;
import org.ttitfly.ttcore.entity.account.Resource;
import org.ttitfly.ttcore.entity.menu.SystemMenu;
import org.ttitfly.ttcore.so.account.ResourceSO;
import org.ttitfly.ttcore.util.exception.DAOException;
import org.ttitfly.ttcore.util.query.ParameterResolver;
import org.ttitfly.ttcore.util.query.PropertyParameterResolver;
import org.ttitfly.ttcore.util.query.SQLBuilder;
import org.ttitfly.ttcore.util.query.SQueryBuilderByHibernate;

/**
 * 用户对象的泛型DAO类.
 * 
 * @author ttitfly
 */
@Component
public class ResourceDao extends HibernateDao<Resource, Long> {
	
	public int getSOResourceViewCount(ResourceSO resourceSO) {
		return Integer.parseInt(getResources4List(resourceSO, true).get(0).toString());

    }

    public List<Resource> getSOResourceView(ResourceSO resourceSO) {
    	return getResources4List(resourceSO,false);
    }
    public List<Resource> getByIds(List<Long> ids) {
		Query query = getSession().createQuery("select o from Resource o where o.id in (:ids) order by o.id");
		query.setParameterList("ids", ids);
		return ( List<Resource> )query.list();
	}
    
    @SuppressWarnings("unchecked")
    private <T> List<T> getResources4List(ResourceSO so, boolean isCount) {
        SQLBuilder pattern = new SQLBuilder("select distinct o ");

        pattern
                .append("FROM Resource o  ");
        if (isCount) {
            pattern = new SQLBuilder("select count(distinct o) ");
            pattern.append("FROM Resource o");
        }

        pattern.append("and upper(o.title) like :%title% ");
        pattern.append("and upper(o.url) like :%url% ");
         if (!isCount) {
        	pattern.append("[alias=o] order by {o.id} desc");
        }

        ParameterResolver resolver = new PropertyParameterResolver(so);
        Query query = null;
        try {
            query = SQueryBuilderByHibernate.buildQuery(getSession(), pattern.toString(), resolver);
        } catch (QueryException e) {
            throw new DAOException(e.getMessage());
        }

        return query.list();
    }
    
    public List<Resource> findAll(){
    	return getAll();
    }

}
